<template>
  <div class="dictionary-management-container">
    <Splitpanes class="default-theme hs">
      <Pane size="40">
        <div style="width: 100%; padding: 10px">
          <div
            style="padding: 20px; color: #000; border-bottom: 1px solid #f4f5f6"
          >
            字典目录
          </div>
          <div class="container" :style="'height:' + height + 'px;'">
            <vxe-grid
              ref="xGridType"
              border
              stripe
              keep-source
              auto-resize
              sync-resize
              :height="height - 30"
              :loading="listLoading"
              size="small"
              :column-config="{ resizable: true }"
              :export-config="{}"
              :columns="tableColumn"
              align="center"
              :show-header="false"
              :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
              :seq-config="{ seqMethod: seqMethod }"
              @current-change="handleDictDataClick"
            >
              <template #form>
                <div style="padding: 10px">
                  <el-button
                    v-permissions="{ permission: ['system:dict:create'] }"
                    class="tree-button"
                    :icon="Plus"
                    type="primary"
                    @click="handleEditType({})"
                  >
                    添加字典分类
                  </el-button>
                  <el-input
                    v-model="queryTypeForm.name"
                    placeholder="请输入字典名称"
                    clearable
                    @input="searchEvent"
                  >
                    <template #append>
                      <el-button
                        v-permissions="{ permission: ['system:dict:export'] }"
                        type="success"
                        plain
                        :loading="dictTypeExportLoading"
                        @click="handleDictTypeExport"
                      >
                        <i class="iconfont-fw ri-download-2-line" />
                        导出
                      </el-button>
                    </template>
                  </el-input>
                </div>
              </template>
              <template #bottom>
                <el-pagination
                  background
                  :current-page="queryTypeForm.pageNo"
                  :layout="layout"
                  small="small"
                  :page-size="queryTypeForm.pageSize"
                  :total="total"
                  @current-change="handleCurrentChange"
                  @size-change="handleSizeChange"
                />
              </template>

              <template #czh="{ row }">
                <el-button
                  v-permissions="{ permission: ['system:dict:update'] }"
                  type="success"
                  link
                  size="small"
                  :icon="Edit"
                  @click="handleEditType(row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-permissions="{ permission: ['system:dict:delete'] }"
                  type="danger"
                  size="small"
                  link
                  :icon="Delete"
                  @click="handleDeleteType(row)"
                >
                  删除
                </el-button>
              </template>
            </vxe-grid>
          </div>
        </div>
      </Pane>
      <Pane>
        <div style="width: 100%; padding: 10px">
          <vxe-grid
            ref="xGridData"
            border
            stripe
            keep-source
            auto-resize
            sync-resize
            :height="height"
            :loading="listLoadingValue"
            size="small"
            :column-config="{ resizable: true }"
            :export-config="{}"
            :columns="tableColumnValue"
            align="center"
            :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
          >
            <template #heandels>
              <el-button
                :disabled="!queryDictDataForm.dictType != ''"
                :icon="Plus"
                type="primary"
                @click="handleEditData({})"
              >
                添加
              </el-button>
            </template>
            <template #czh="{ row }">
              <el-button
                type="primary"
                size="small"
                link
                :icon="Edit"
                @click="handleEditData(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                link
                :icon="Delete"
                @click="handleDeleteData(row)"
              >
                删除
              </el-button>
            </template>
            <template #bottom>
              <el-pagination
                background
                :current-page="queryDictDataForm.pageNo"
                :layout="layout"
                small="small"
                :page-size="queryDictDataForm.pageSize"
                :total="dictDataTotal"
                @current-change="handleDictDataCurrentChange"
                @size-change="handleDictDataChange"
              />
            </template>
          </vxe-grid>
        </div>
      </Pane>
    </Splitpanes>
    <dictTypeEdit ref="dictTypeEditref" @fetch-data="fetchDictType" />
    <dictDataEdit ref="dictDataEditref" @fetch-data="fetchDictData" />
  </div>
</template>

<script>
  import { Splitpanes, Pane } from 'splitpanes'
  import 'splitpanes/dist/splitpanes.css'
  import {
    getDictTypePage,
    exportDictType,
    deleteDictType,
  } from '@/api/system/dict/dict.type'
  import {
    getDictDataPage,
    exportDictData,
    deleteDictData,
  } from '@/api/system/dict/dict.data'
  import download from '@/utils/download'
  import { Plus, Edit, Delete } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'Dict',
    components: {
      dictTypeEdit: defineAsyncComponent(() =>
        import('./components/dictTypeEdit')
      ),
      dictDataEdit: defineAsyncComponent(() =>
        import('./components/dictDataEdit')
      ),
      Splitpanes,
      Pane,
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const $baseTableHeight = inject('$baseTableHeight')
      const $XEUtils = inject('$XEUtils')
      const state = reactive({
        height: $baseTableHeight(0),
        dictTypeExportLoading: false,
        xGridType: null,
        xGridData: null,
        dictTypeEditref: null,
        dictDataEditref: null,
        tableColumn: [
          { type: 'seq', width: 50, fixed: 'left' },
          {
            field: 'name',
            title: '字典名称',
            showOverflow: true,
            minWidth: 120,
            fixed: 'left',
          },
          {
            field: 'type',
            title: '字典类型',
            showOverflow: true,
            minWidth: 120,
            fixed: 'left',
          },
          {
            title: '',
            showOverflow: true,
            width: 170,
            slots: {
              default: 'czh',
            },
            fixed: 'right',
          },
        ],
        tableColumnValue: [
          { type: 'seq', width: 50, fixed: 'left' },
          {
            field: 'label',
            title: '字典标签',
            showOverflow: true,
            width: 120,
            fixed: 'left',
          },
          {
            field: 'value',
            title: '字典键值',
            showOverflow: true,
            width: 230,
          },
          {
            field: 'colorType',
            title: '颜色类型',
            showOverflow: true,
            width: 120,
          },
          {
            field: 'cssClass',
            title: 'CSS Class',
            showOverflow: true,
            width: 80,
          },
          {
            field: 'createTime',
            title: '创建时间',
            showOverflow: true,
            width: 120,
            formatter: ['formatDate', 'yyyy-MM-dd HH:mm:ss'],
          },
          {
            title: '',
            showOverflow: true,
            width: 170,
            slots: {
              default: 'czh',
              header: 'heandels',
            },
            fixed: 'right',
          },
        ],
        layout: 'total, prev, pager, next, jumper',
        total: 0,
        queryTypeForm: {
          pageNo: 1,
          pageSize: 30,
          name: '',
        },
        dictDataTotal: 0,
        queryDictDataForm: {
          pageNo: 1,
          pageSize: 30,
          dictType: '',
        },
        listLoading: true,
        listLoadingValue: false,
        isRoot: true,
      })

      const handleEditType = (row) => {
        state['dictTypeEditref'].showEdit(row)
      }

      const handleEditData = (row) => {
        if (row.id) {
          state['dictDataEditref'].showEdit(row)
        } else {
          const rows = state['xGridType'].getCurrentRecord()
          state['dictDataEditref'].showEdit({
            dictType: state.queryDictDataForm.dictType,
          })
        }
      }

      const handleDeleteType = (row) => {
        if (row.id) {
          state.listLoading = true
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { code, msg, data } = await deleteDictType(row.id).catch(
              (err) => {
                state.listLoadingValue = false
              }
            )
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchDictType()
          })
        }
      }

      const handleDeleteData = (row) => {
        if (row.id) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { code, data, msg } = await deleteDictData(row.id).catch(
              (err) => {
                state.listLoadingValue = false
              }
            )
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchDictData()
          })
        }
      }

      const fetchDictType = async () => {
        state.listLoading = true
        getDictTypePage(state.queryTypeForm)
          .then((res) => {
            if (res.code == 0 || res.code == 200) {
              state['xGridType'].reloadData(res.data.list)
              state.total = res.data.total
              state.listLoading = false
            } else {
              state.listLoading = false
            }
          })
          .catch((err) => {
            state.listLoading = false
          })
      }

      const fetchDictData = async () => {
        state.listLoadingValue = true
        getDictDataPage(state.queryDictDataForm)
          .then((res) => {
            if (res.code == 0 || res.code == 200) {
              state['xGridData'].reloadData(res.data.list)
              state.dictDataTotal = res.data.total
              state.listLoadingValue = false
            } else {
              state.listLoadingValue = false
            }
          })
          .catch((err) => {
            state.listLoadingValue = false
          })
      }

      const searchEvent = (e) => {
        state.queryTypeForm = {
          pageNo: 1,
          pageSize: 30,
          name: $XEUtils.toValueString(e).trim().toLowerCase(),
        }
        fetchDictType()
      }

      const handleDictDataClick = ({
        newValue,
        oldValue,
        row,
        rowIndex,
        $rowIndex,
        column,
        columnIndex,
        $columnIndex,
        $event,
      }) => {
        state.isRoot = false
        state.queryDictDataForm = {
          pageNo: 1,
          pageSize: 30,
          dictType: row.type,
        }
        fetchDictData()
      }

      const remove = (node, data) => {
        const parent = node.parent
        const children = parent.data.children || parent.data
        const index = children.findIndex((d) => d.id === data.id)
        children.splice(index, 1)
        state.data = [...state.data]
      }

      const handleSizeChange = (val) => {
        state.queryTypeForm.pageSize = val
        fetchDictType()
      }

      const handleCurrentChange = (val) => {
        state.queryTypeForm.pageNo = val
        fetchDictType()
      }

      const seqMethod = ({ row, rowIndex, column, columnIndex }) => {
        return (
          (state.queryTypeForm.pageNo - 1) * state.queryTypeForm.pageSize +
          rowIndex +
          1
        )
      }

      const handleDictDataChange = (val) => {
        state.queryDictDataForm.pageSize = val
        fetchDictData()
      }

      const handleDictDataCurrentChange = (val) => {
        state.queryDictDataForm.pageNo = val
        fetchDictData()
      }

      const DictDataSeqMethod = ({ row, rowIndex, column, columnIndex }) => {
        return (
          (state.queryDictDataForm.pageNo - 1) * state.queryTypeForm.pageSize +
          rowIndex +
          1
        )
      }

      const handleDictTypeExport = async () => {
        state.exportLoading = true
        const data = await exportDictType(state.queryTypeForm)
        download.excel(data, '自典名称数据.xls')
        state.exportLoading = false
      }

      onMounted(() => {
        fetchDictType()
      })

      onBeforeMount(() => {
        window.addEventListener('resize', handleHeight)
      })

      onBeforeUnmount(() => {
        window.removeEventListener('resize', handleHeight)
      })

      const handleHeight = () => {
        state.height = $baseTableHeight(0)
      }

      return {
        ...toRefs(state),
        remove,
        handleEditType,
        handleEditData,
        handleDeleteType,
        handleDeleteData,
        seqMethod,
        fetchDictType,
        fetchDictData,
        handleDictDataClick,
        handleSizeChange,
        handleCurrentChange,
        handleDictDataChange,
        handleDictDataCurrentChange,
        DictDataSeqMethod,
        searchEvent,
        Plus,
        Edit,
        Delete,
        handleDictTypeExport,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.dictionary-management';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;

    .tree-button {
      width: 100%;
      margin-bottom: $base-margin;
    }

    :deep() {
      .el-tree {
        margin-top: $base-margin;

        &-node__label {
          display: block;
          width: 100%;
        }
      }
    }
  }
</style>
